<style scoped>
  .el-table >>> .cell {
    max-height: 100px;
    overflow: auto;
  }
</style>

<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="文本消息" prop="departId">-->
<!--        <el-input-->
<!--          v-model="queryParams.departId"-->
<!--          placeholder="请输入文本消息"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="所属分组" prop="departName">
        <el-input
          v-model="queryParams.departName"
          placeholder="请输入所属分组"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关键词" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键词"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['system:article:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['system:article:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:article:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:article:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属分组" align="center" prop="departName" />
      <el-table-column label="关键词" align="center" prop="keyword" />
      <el-table-column label="文本消息" align="center" width="260" prop="message">
        <template slot-scope="scope">
          <div v-html="scope.row.message"></div>
        </template>
      </el-table-column>
      <el-table-column label="图文消息" align="center" width="200" prop="newsTitle">
        <template slot-scope="scope">
          <div v-html="scope.row.newsTitle"></div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="修改时间" align="center" prop="updateTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['system:article:edit']"-->
<!--          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:article:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改消息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属分组" prop="department">
          <el-select v-model="form.department" placeholder="请选择">
            <el-option
              v-for="item in departments"
              :key="item.id"
              :label="item.name"
              :value="item">
            </el-option>
          </el-select>
<!--          <el-input v-model="form.departName" placeholder="请输入所属分组" />-->
        </el-form-item>
        <el-form-item label="关键词" prop="keyword">
          <el-input v-model.lazy="form.keyword" placeholder="请输入关键词" />
        </el-form-item>
        <el-form-item label="文本消息" prop="message">
          <el-input type="textarea"  v-model="form.message" placeholder="请输入关键词" />
<!--          <div ref="editor" style="height: 175px;"></div>-->
<!--          <el-input v-model="form.message" type="textarea" placeholder="请输入内容" />-->
        </el-form-item>
<!--        <el-form-item label="图文消息" prop="news">-->
<!--          <el-button @click="showNewsList">获取图文消息</el-button>-->
<!--          <el-drawer-->
<!--            append-to-body-->
<!--            class="rj-drawer"-->
<!--            title="我是标题"-->
<!--            :visible.sync="drawer"-->
<!--            :with-header="false">-->
<!--            <span>我来啦!</span>-->
<!--          </el-drawer>-->
<!--        </el-form-item>-->
        <el-form-item label="图文消息" prop="news">
          <el-select v-model="news" placeholder="请选择">
            <el-option
              v-for="item in cities"
              :key="item.value"
              :label="item.label"
              :value="item.value">
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listArticle, getArticle, delArticle, addArticle, updateArticle, exportArticle, exist } from "@/api/system/article";
import { listAllDepart } from "@/api/system/department";

export default {
  name: "Article",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 消息表格数据
      articleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        departId: null,
        departName: null,
        keyword: null,
        message: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        department: [
          { required: true, message: "部门不能为空", trigger: "change" }
        ],
        keyword: [
          { required: true, message: "关键词不能为空", trigger: "blur" }
        ],
        message: [
          { required: true, message: "文本消息不能为空", trigger: "blur" }
        ]
      },
      departments: [],
      department: '',
      title: '',
      quill: null,
      drawer: false,
      news: '',
      cities: [{
        value: 'Beijing',
        label: '北京'
      }, {
        value: 'Shanghai',
        label: '上海'
      }, {
        value: 'Nanjing',
        label: '南京'
      }, {
        value: 'Chengdu',
        label: '成都'
      }, {
        value: 'Shenzhen',
        label: '深圳'
      }, {
        value: 'Guangzhou',
        label: '广州'
      }],
    };
  },
  created() {
    this.getList();
    this.getDeparts();
  },
  mounted() {
  },
  watch: {
    'form.department': function (val) {
      if (!val) return;
      this.form.departName = val.name;
      this.form.departId = val.id;
    },
    'form.keyword': async function (val) {
      if (!val) return;
      let count = await this.checkExist();
      if (this.form.id != null) {
        if (count > 1) {
          this.msgInfo("该关键词已存在，不能重复设置");
          this.form.keyword = '';
        }
      } else {
        if (count > 0) {
          this.msgInfo("该关键词已存在，不能重复设置");
          this.form.keyword = '';
        }
      }
    },
    quill: function (val) {
      if (val == '' || val == null) return;
      let that = this;
      this.quill.on('text-change', function(delta, oldDelta, source) {
        // that.form.message = that.quill.root.innerHTML;
        that.form.message = that.quill.getContent();
      });
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    showNewsList() {
      this.drawer = true;
    },
    uploadImg() {
      this.$refs.editor.renderImg(
        'https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top-e3b63a0b1b.png'
      )
    },
    contentChange(w) {
      console.log('TCL: contentChange -> w', w)
    },
    titleChange(w) {
      console.log('TCL: titleChange -> w', w)
    },
    /** 查询消息列表 */
    getList() {
      this.loading = true;
      listArticle(this.queryParams).then(response => {
        this.articleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询分组列表 */
    getDeparts() {
      listAllDepart().then(response => {
        this.departments = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        departId: null,
        departName: null,
        keyword: null,
        message: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加消息";

      // this.$nextTick(() => {
      //   if (!this.quill) {
      //     this.quill = this.initEditor(this)
      //   }
      // })
    },
    initEditor: (that) => {
      return new Quill(that.$refs.editor, {
        modules: {
          toolbar: [
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],        // 标题字体
            [{ 'font': [] }],                                 // 字体
            ['bold', 'italic', 'underline', 'strike'],        // 切换按钮
            [{ 'align': [] }],                                // 对齐方式
            ['blockquote', 'code-block'],                     // 文本块/代码块
            [{ 'header': 1 }, { 'header': 2 }],               // 用户自定义按钮值
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],     // 有序/无序列表
            [{ 'script': 'sub'}, { 'script': 'super' }],      // 上标/下标
            [{ 'indent': '-1'}, { 'indent': '+1' }],          // 减少缩进/缩进
            [{ 'color': [] }, { 'background': [] }],          // 主题默认下拉，使用主题提供的值
            ['clean'],                                        // 清除格式
            ['image', 'link', 'video']                        // 图片 / 链接 / 视频
          ]
        },
        placeholder: '请输入消息内容',
        theme: 'snow'  // or 'bubble'
      });
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      let that = this;
      this.reset();
      const id = row.id || this.ids
      await getArticle(id).then(response => {
        this.form = response.data;
        this.form.department = {
          name: response.data.departName,
          id: response.data.departId
        };
        this.open = true;
        this.title = "修改消息";
      });
      // this.$nextTick(() => {
      //   if (!this.quill) {
      //     this.quill = this.initEditor(this);
      //   }
      //   this.quill.setContent(this.form.message);
      //   // this.quill.root.innerHTML = this.form.message;
      // })
    },
    async checkExist() {
      let count = 0;
      await listArticle({"keyword": this.form.keyword}).then(response => {
        count = response.total;
      });
      return count;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateArticle(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArticle(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除消息编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delArticle(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有消息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportArticle(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
